import asyncio
import json
from typing import List, Dict, Any
from llm.llm_client import quick_chat
from common.config import LLM_CONFIG, USE_SILICONFLOW
from common.dict_manager import get_dict_name_cached
from common.authority_extractor import extract_gbglqx
from common.clean_llm_result import clean_llm_result
from prompts.system_prompts import get_system_prompt


async def extract_fyrs(case_content: str) -> List[Dict[str, Any]]:
    """
    提取反映人信息

    Args:
        case_content: 信访件内容

    Returns:
        反映人信息列表
    """
    try:
        print("开始提取反映人信息...")

        # 获取系统提示词
        system_prompt = get_system_prompt("laixin_fyr")

        # 调用模型提取反映人信息
        if USE_SILICONFLOW:
            print(
                f"使用硅基流动配置: {LLM_CONFIG['BASE_URL_dev']}, 模型: {LLM_CONFIG['MODEL_dev']}"
            )
            result = quick_chat(
                base_url=LLM_CONFIG["BASE_URL_dev"],
                model=LLM_CONFIG["MODEL_dev"],
                api_key=LLM_CONFIG["API_KEY"],
                system_prompt=system_prompt,
                user_prompt=case_content,
                temperature=0.1,
                max_tokens=2000,
            )
        else:
            print(
                f"使用原有配置: {LLM_CONFIG['BASE_URL_1244']}, 模型: {LLM_CONFIG['MODEL_72B']}"
            )
            result = quick_chat(
                base_url=LLM_CONFIG["BASE_URL_1244"],
                model=LLM_CONFIG["MODEL_72B"],
                system_prompt=system_prompt,
                user_prompt=case_content,
                temperature=0.1,
                max_tokens=2000,
            )

        # 解析返回的JSON
        fyrs_text = result.text.strip()
        print(f"反映人提取原始结果: {fyrs_text}")

        # 清洗模型输出，移除think标签和Markdown代码块标记
        cleaned_fyrs_text = clean_llm_result(fyrs_text)
        print(f"清洗后的反映人结果: {cleaned_fyrs_text}")

        # 尝试解析JSON
        try:
            fyrs_data = json.loads(cleaned_fyrs_text)
            if not isinstance(fyrs_data, list):
                fyrs_data = [fyrs_data]
        except json.JSONDecodeError as e:
            print(f"解析反映人JSON失败: {str(e)}")
            # 尝试更宽松的解析方式
            try:
                # 查找JSON数组的开始和结束位置
                start_idx = cleaned_fyrs_text.find("[")
                end_idx = cleaned_fyrs_text.rfind("]")
                if start_idx != -1 and end_idx != -1:
                    json_content = cleaned_fyrs_text[start_idx : end_idx + 1]
                    fyrs_data = json.loads(json_content)
                    print("通过宽松解析成功提取JSON数据")
                else:
                    print("无法找到有效的JSON数组，返回空列表")
                    return []
            except Exception as e2:
                print(f"宽松解析也失败: {str(e2)}")
                return []

        # 对每个反映人进行字典转换
        processed_fyrs = []
        for fyr in fyrs_data:
            if isinstance(fyr, dict):
                processed_fyr = fyr.copy()

                # 转换职级
                if "zj" in processed_fyr and processed_fyr["zj"]:
                    converted_zj = get_dict_name_cached("职级", processed_fyr["zj"])
                    processed_fyr["zj"] = converted_zj if converted_zj else ""

                # 转换政治面貌
                if "zzmm" in processed_fyr and processed_fyr["zzmm"]:
                    converted_zzmm = get_dict_name_cached(
                        "政治面貌", processed_fyr["zzmm"]
                    )
                    processed_fyr["zzmm"] = converted_zzmm if converted_zzmm else ""

                processed_fyrs.append(processed_fyr)

        print(f"反映人信息处理完成，共 {len(processed_fyrs)} 人")
        return processed_fyrs

    except Exception as e:
        print(f"提取反映人信息失败: {str(e)}")
        return []


async def extract_bfyrs(case_content: str) -> List[Dict[str, Any]]:
    """
    提取被反映人信息

    Args:
        case_content: 信访件内容

    Returns:
        被反映人信息列表
    """
    try:
        print("开始提取被反映人信息...")

        # 获取系统提示词
        system_prompt = get_system_prompt("laixin_bfyr")

        # 调用模型提取被反映人信息
        if USE_SILICONFLOW:
            print(
                f"使用硅基流动配置: {LLM_CONFIG['BASE_URL_dev']}, 模型: {LLM_CONFIG['MODEL_dev']}"
            )
            result = quick_chat(
                base_url=LLM_CONFIG["BASE_URL_dev"],
                model=LLM_CONFIG["MODEL_dev"],
                api_key=LLM_CONFIG["API_KEY"],
                system_prompt=system_prompt,
                user_prompt=case_content,
                temperature=0.1,
                max_tokens=2000,
            )
        else:
            print(
                f"使用原有配置: {LLM_CONFIG['BASE_URL_1244']}, 模型: {LLM_CONFIG['MODEL_72B']}"
            )
            result = quick_chat(
                base_url=LLM_CONFIG["BASE_URL_1244"],
                model=LLM_CONFIG["MODEL_72B"],
                system_prompt=system_prompt,
                user_prompt=case_content,
                temperature=0.1,
                max_tokens=2000,
            )

        # 解析返回的JSON
        bfyrs_text = result.text.strip()
        print(f"被反映人提取原始结果: {bfyrs_text}")

        # 清洗模型输出，移除think标签和Markdown代码块标记
        cleaned_bfyrs_text = clean_llm_result(bfyrs_text)
        print(f"清洗后的被反映人结果: {cleaned_bfyrs_text}")

        # 尝试解析JSON
        try:
            bfyrs_data = json.loads(cleaned_bfyrs_text)
            if not isinstance(bfyrs_data, list):
                bfyrs_data = [bfyrs_data]
        except json.JSONDecodeError as e:
            print(f"解析被反映人JSON失败: {str(e)}")
            # 尝试更宽松的解析方式
            try:
                # 查找JSON数组的开始和结束位置
                start_idx = cleaned_bfyrs_text.find("[")
                end_idx = cleaned_bfyrs_text.rfind("]")
                if start_idx != -1 and end_idx != -1:
                    json_content = cleaned_bfyrs_text[start_idx : end_idx + 1]
                    bfyrs_data = json.loads(json_content)
                    print("通过宽松解析成功提取JSON数据")
                else:
                    print("无法找到有效的JSON数组，返回空列表")
                    return []
            except Exception as e2:
                print(f"宽松解析也失败: {str(e2)}")
                return []

        # 对每个被反映人进行处理
        processed_bfyrs = []
        for bfyr in bfyrs_data:
            if isinstance(bfyr, dict):
                processed_bfyr = bfyr.copy()

                # 拼装被反映人信息：职级、职务、单位或地址
                zj = processed_bfyr.get("zj", "")
                zw = processed_bfyr.get("zw", "")
                dwhdz = processed_bfyr.get("dwhdz", "")

                # 构建完整信息字符串（仅用于构建干部管理权限请求提示词）
                info_parts = []
                if zj:
                    info_parts.append(f"职级：{zj}")
                if zw:
                    info_parts.append(f"职务：{zw}")
                if dwhdz:
                    info_parts.append(f"单位或地址：{dwhdz}")

                # 临时保存完整信息用于构建提示词
                temp_complete_info = "，".join(info_parts) if info_parts else ""

                # 检查是否需要提取干部管理权限
                if zj and zw and dwhdz:
                    print(
                        f"为被反映人 {processed_bfyr.get('mc', '')} 提取干部管理权限..."
                    )

                    # 构建用户提示词
                    user_prompt = f"""
                    被反映人信息：
                    姓名：{processed_bfyr.get('mc', '')}
                    职级：{zj}
                    职务：{zw}
                    单位或地址：{dwhdz}
                    
                    请根据以上信息提取干部管理权限。
                    """

                    # 提取干部管理权限
                    try:
                        gbglqx_result = await extract_gbglqx(
                            json.dumps([processed_bfyr])
                        )
                        if gbglqx_result:
                            gbglqx_data = json.loads(gbglqx_result)
                            if gbglqx_data and len(gbglqx_data) > 0:
                                raw_gbglqx = gbglqx_data[0].get("gbglqx", "")
                                # 转换干部管理权限字典
                                if raw_gbglqx:
                                    converted_gbglqx = get_dict_name_cached(
                                        "干部管理权限", raw_gbglqx
                                    )
                                    processed_bfyr["gbglqx"] = (
                                        converted_gbglqx if converted_gbglqx else ""
                                    )
                                else:
                                    processed_bfyr["gbglqx"] = ""
                            else:
                                processed_bfyr["gbglqx"] = ""
                        else:
                            processed_bfyr["gbglqx"] = ""
                    except Exception as e:
                        print(f"提取干部管理权限失败: {str(e)}")
                        processed_bfyr["gbglqx"] = ""
                else:
                    processed_bfyr["gbglqx"] = ""

                # 转换职级
                if "zj" in processed_bfyr and processed_bfyr["zj"]:
                    converted_zj = get_dict_name_cached("职级", processed_bfyr["zj"])
                    processed_bfyr["zj"] = converted_zj if converted_zj else ""

                # 移除临时字段，不返回给前端
                if "完整信息" in processed_bfyr:
                    del processed_bfyr["完整信息"]

                processed_bfyrs.append(processed_bfyr)

        print(f"被反映人信息处理完成，共 {len(processed_bfyrs)} 人")
        return processed_bfyrs

    except Exception as e:
        print(f"提取被反映人信息失败: {str(e)}")
        return []
